//
//  MusicPlayerDetailsViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/25.
//

import UIKit

class MusicPlayerDetailsViewController: BaseViewController {
    let disposeBag = DisposeBag()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.removeSubViewController_k(vcName: "MusicGenerateViewController")
    }
    
    var model:MusicModel? {
        didSet {
            playerView.setup(model: model)
        }
    }
    
   lazy  var playerView: MusicPlayerView = {
       let view = MusicPlayerView()
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(playerView)

        playerView.historyBtn.setClosureTouchUpInside_k { [weak self] in
            let vc = MusicHistoryViewController()
            self?.navigationController?.pushViewController(vc)
        }
        
        playerView.backBtn.setClosureTouchUpInside_k { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        MusicPlayerManager.shared.dataSource = []
        MusicPlayerManager.shared.startPlayMusic(model: model)
        
        GlobalRx.updateMusicInfo.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] model in
            self?.playerView.setup(model: model)
        }).disposed(by: disposeBag)
        
        GlobalRx.playStateSubject.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] status in
             if status == .SUPlayerStatePlaying {
                  self?.playerView.playBtn.isSelected = true
//                  self?.playView.resumeRotation()
             }else {
                  self?.playerView.playBtn.isSelected = false
//                  self?.playView.pauseRotation()
             }
        }).disposed(by: disposeBag)
        
        GlobalRx.updateMusicProgress.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] currend, total, progress in
             self?.playerView.cuLb.text = currend
             self?.playerView.toLb.text = total
             self?.playerView.musicSlider.value = progress
        }).disposed(by: disposeBag)
        
        
        
        playerView.playBtn.setClosureTouchUpInside_k { [weak self] in
            if MusicPlayerManager.shared.playState == .SUPlayerStatePlaying {
                MusicPlayerManager.shared.pauseCurrentMusic()
            }else {
                MusicPlayerManager.shared.playCurrentMusic()
            }
        }
        
        playerView.shareBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
//            self.shareAudio(urlString: self.model?.share_page ?? "", viewController: self)
            self.shareLinkWithCover(urlString: self.model?.share_page ?? "", viewController: self)
        }
        
        playerView.rightBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.navigationController?.popToRootViewController(animated: true)
        }
        
        playerView.saveBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.shareAudio(urlString: self.model?.music_url ?? "", viewController: self)
        }
        
    }
    func shareLinkWithCover(urlString: String, viewController: UIViewController) {
        guard let url = URL(string: urlString) else { return }

        // 创建一个包含链接和封面图片的数组
        let itemsToShare: [Any] = [url]
        
        // 创建分享活动视图控制器
        let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
        
        // 排除某些活动类型（根据需要）
        activityViewController.excludedActivityTypes = [
            .assignToContact,
            .saveToCameraRoll,
            .addToReadingList,
            .postToVimeo
        ]
        
        // 显示分享界面
        viewController.present(activityViewController, animated: true, completion: nil)
    }

    
    func shareAudio(urlString: String, viewController: UIViewController) {
        guard let url = URL(string: urlString) else { return }
        // 创建并显示加载指示器
        NDProgressHUD.showLoading()
        // 下载音频文件到本地
        let downloadTask = URLSession.shared.downloadTask(with: url) { (location, response, error) in
            DispatchQueue.main.async {
                // 隐藏加载指示器
                NDProgressHUD.hide()
            }
            guard let location = location, error == nil else {
                print("下载音频文件失败: \(error?.localizedDescription ?? "未知错误")")
                return
            }
            // 创建文件管理器
            let fileManager = FileManager.default
            // 将文件移动到临时目录
            let destinationURL = fileManager.temporaryDirectory.appendingPathComponent(response?.suggestedFilename ?? url.lastPathComponent)
            do {
                // 如果文件已经存在，删除它
                if fileManager.fileExists(atPath: destinationURL.path) {
                    try fileManager.removeItem(at: destinationURL)
                }
                // 移动下载的文件到目标路径
                try fileManager.moveItem(at: location, to: destinationURL)
                // 在主线程中展示分享界面
                DispatchQueue.main.async {
                    let activityViewController = UIActivityViewController(activityItems: [destinationURL], applicationActivities: nil)
                    
                    // 排除某些活动类型（根据需要）
                    activityViewController.excludedActivityTypes = [
                        .assignToContact,
                        .saveToCameraRoll,
                        .addToReadingList,
                        .postToVimeo
                    ]
                    
                    // 显示分享界面
                    viewController.present(activityViewController, animated: true, completion: nil)
                }
            } catch {
                print("移动音频文件失败: \(error.localizedDescription)")
            }
        }
        
        // 开始下载任务
        downloadTask.resume()
    }
    deinit {
        MusicPlayerManager.shared.removeCurrent()
    }
}
